package utils

import (
	"runtime"
)

type IUpdate interface {
	Update()
}

type TimetickCore struct {
	count    int64
	interval int
	cf       IUpdate
	isStop   bool
	isLockOS bool
}

func NewTimetickCore(intv int, LockOS bool, cf IUpdate) *TimetickCore {
	return &TimetickCore{interval: intv, isLockOS: LockOS, cf: cf}
}

func (m *TimetickCore) Run() {
	go m.loop()
}

func (m *TimetickCore) Stop() {
	m.isStop = true
}

func (m *TimetickCore) IsStop() bool {
	return m.isStop
}

func (m *TimetickCore) loop() {
	if m.isLockOS {
		runtime.LockOSThread()
	}

	t := NewIntervalSleep(m.interval)

	for !m.IsStop() {
		t.Start()
		m.cf.Update()
		t.Sleep()
	}
}
